<template>
  <div class="yh-main">
    <div>
      <video ref="audio" controls style="display: none"/>
    </div>
    <iframe
      class="scrollbar"
      id="scrollbar"
      ref="iframe"
      scrolling="none"
      :width="iframeSize.width"
      :height="iframeSize.height"
      :src="fileUrl"/>
  </div>
</template>

<script>
import dayjs from "dayjs";
import {EnumConstants, IframeBizTypeEnum} from "@/enums/bizTypeEnum";
import {AndroidLocalSdkUtil} from "@/sdk/AndroidLocalSdkUtil";
import {WebSocketManager} from "@/sdk/WebSocketManager";
import {UserCommitApi} from "@/api/user_common";

export default {
  name: "",
  components: {},
  data() {
    return {
      // 终端信息
      sbInfo: {},
      // 虚拟设备
      virtualSbInfo: {},
      terminalId: "",
      terminalType: "",
      volume: 3,
      waitNum: 3,
      // 终端模板
      moduleInfo: {},
      isSuccess: false,
      devType: 1,
      previewType: "",
      sync: "2",
      workerIds: [],
      // 分组
      groupData: [],
      // 定时器
      timerTask: null,
      pageSize: 5,
      switchSeconds: 10,
      socketManager: null,
      androidLocalSdkUtil: null,
      fileUrl: "",
      iframeSize: {
        height: "100%",
        width: "100%"
      },
      audioInfo:null,
    };
  },
  mounted() {
    // 初始化参数
    this.initParams();
    // 获取模板信息
    this.init();
  },
  methods: {
    /**
     * 接收路由参数
     */
    initParams() {
      const searchParams = this.$route.query;
      if (searchParams.terminalId) {
        this.terminalId = searchParams.terminalId;
      }
      if (searchParams.terminalType) {
        this.terminalType = searchParams.terminalType;
      }
      if (searchParams.terminalId) {
        this.terminalId = searchParams.terminalId;
      }

      if (searchParams.devType) {
        this.devType = searchParams.devType;
      }
      if (searchParams.previewType) {
        this.previewType = searchParams.previewType;
      }

      if (searchParams.sync) {
        this.sync = searchParams.sync;
      }
      this.isSuccess = true;

    },
    /**
     * 获取模板数据
     */
    async init() {
      try {
        this.audioInfo = this.$refs.audio;
        // 参数获取到后再放行
        if (this.isSuccess === false) {
          return;
        }
        this.androidLocalSdkUtil = new AndroidLocalSdkUtil(this);
        // 注册
        window.android = this.androidLocalSdkUtil;
        // 获取设备信息
        await this.androidLocalSdkUtil.getSbInfo();
        // 模板信息
        await this.androidLocalSdkUtil.getModelDetail();

        if (this.moduleInfo && this.moduleInfo.url) {
          let iframeUrl = "";
          if (!this.moduleInfo.tplType || !this.moduleInfo.tplType === 0) {
            iframeUrl = this.moduleInfo.indexUrl + this.moduleInfo.url;
          } else {
            iframeUrl = this.moduleInfo.url;
          }
          if((process.env.NODE_ENV) === 'development'){
            iframeUrl = "/#/tempView";
          }
          // 加载页面 模拟安卓 webView
          this.fileUrl = iframeUrl + "?devType=" + this.devType + "&modelId=" + this.moduleInfo.id + "&previewType=" + this.previewType + "&t=" + new Date().getTime();
        }

        // 建立socket 连接
        this.onLine();

        // 如果需要同步终端，则5S 后进行同步
        if (this.sync === "1") {
          console.warn("注意：____________10S后即将同步实时终端缓存！");
          setTimeout(function () {
            console.warn("注意：____________开始执行同步请求：同步实时终端缓存！");
            this.getTrueTerminalData({
              terminalId: this.terminalId,
              terminalType: this.terminalType
            });
          }, 10000);
        }

        setInterval(() => {
          this.androidLocalSdkUtil.sendSetDateMsg(this.getNowDateInfo());
        }, 60 * 1000);
        this.androidLocalSdkUtil.sendSetDateMsg(this.getNowDateInfo());
      } catch (e) {

      }
    },
    /**
     * 获取时间
     * @returns {{date: string, week: string, time: string, timestamp: number}}
     */
    getNowDateInfo() {
      let date = new Date();
      let week = ["日", "一", "二", "三", "四", "五", "六"];
      let time = dayjs(date).format("HH:mm:ss").split(":");
      return {
        "date": dayjs(date).format("YYYY-MM-DD"),
        "timestamp": dayjs(date).unix(),
        "week": "星期" + week[dayjs(date).day()],
        "time": time[0] + ":" + time[1]
      };
    },
    /**
     * 获取终端数据
     * @param item
     */
    getTrueTerminalData(item) {
      UserCommitApi.getScreenCurrentDataInfo({
        terminalId: item.terminalId,
        terminalType: item.terminalType,
        uuid: this.socketManager.uuidNo
      });
    },

    onLine() {
      let _this = this;
      let host = location.host;
      if((process.env.NODE_ENV) === 'development'){
        host = "192.168.31.42:7000";
      }
      this.socketManager = new WebSocketManager({
        ipPort: host + "/clinic/websocket",
        terminalType: this.terminalType,
        terminalId: this.terminalId
      }, async function (r) {
        if (r && r.data && r.data !== "pong") {
          let msgData = JSON.parse(r.data);
          console.log("收到服务端发送消息：________________ " + r.data);
          // 上屏消息
          switch (msgData.msgCode) {
            case  "Qcss_Login_Msg" :
              if (_this.terminalType === "2") {
                await _this.androidLocalSdkUtil.WaitList();
                // 数据分组
                await _this.androidLocalSdkUtil.getGroupData();
                // 初始化定时器
                await _this.androidLocalSdkUtil.initTimerTask();
              }
              window.webSDKServices({
                bizType: "doctorLogin",
                msgContent: JSON.stringify(msgData)
              });
              break;
            case  "Qcss_LoginOut_Msg" :
              if (_this.terminalType === "2") {
                await _this.androidLocalSdkUtil.WaitList();
                // 数据分组
                await _this.androidLocalSdkUtil.getGroupData();
                // 初始化定时器
                await _this.androidLocalSdkUtil.initTimerTask();
              }
              window.webSDKServices({
                bizType: "doctorLogout",
                msgContent: JSON.stringify(msgData)
              });
              break;
            case  "Qcss_Call_Up_Msg" :
              _this.play(msgData);
              break;
            default :
          }
          window.webSDKServices({
            bizType: EnumConstants[IframeBizTypeEnum[this.terminalType].value][msgData.msgCode] || msgData.msgCode,
            msgContent: r.data
          });
        }
      });

      this.socketManager.start();
    },

    play(msgData) {
      let msgContent = msgData.msgContent;
      let voiceArr = [];
      // 就诊语音播放
      if (msgContent.treatingVoice && msgContent.treatingVoicePlayUrl) {
        let treatingVoiceCount = msgContent.treatingVoiceCount || 1;
        let number = Number(treatingVoiceCount);
        for (let i = 0; i < number; i++) {
          if (msgContent.treatingVoicePlayUrl !== "") {
            voiceArr.push({
              path: msgContent.treatingVoicePlayUrl
            });
          }
        }
      }
      // 候诊语音播放
      if (msgContent.waitingVoice && msgContent.waitingVoicePlayUrl) {
        let waitingVoiceCount = msgContent.waitingVoiceCount || 1;
        let number = Number(waitingVoiceCount);
        for (let i = 0; i < number; i++) {
          if (msgContent.waitingVoicePlayUrl !== "") {
            voiceArr.push({
              path: msgContent.waitingVoicePlayUrl
            });
          }
        }
      }
      // 消息类型
      let msgCode = EnumConstants[IframeBizTypeEnum[this.terminalType].value][msgData.msgCode] || msgData.msgCode;
      msgCode.split(",").forEach((bizType) => {
        // 候诊弹窗 就诊弹窗
        if ((msgContent.waitingAlert || msgContent.treatingAlert) && bizType === "openMsgWin") {
          window.webSDKServices({
            bizType: bizType,
            msgContent: JSON.stringify(msgData)
          });
        } else {
          window.webSDKServices({
            bizType: bizType,
            msgContent: JSON.stringify(msgData)
          });
        }
      });
      let start = 0;

      // 配置是否展示就诊弹窗/候诊弹窗
      let elem = this.$refs.audio;
      elem.src = voiceArr[start].path;
      elem.addEventListener("ended", function () {
        start++;
        if (start < voiceArr.length) {
          elem.src = voiceArr[start].path;
          if (elem.paused) {
            elem.play();
          } else {
            elem.pause();
          }
        } else {
          start = 0;
          voiceArr = [];
          // 关闭弹窗
          window.webSDKServices({
            bizType: "closeMsgWin",
            msgContent: ""
          });
        }
      });
      elem.play();
    },
  }
};
</script>
<style>
.yh-main {
  height: 100%;
}
</style>
